"""
2.	近年来，汽车车牌检测已经越来越受到人们的重视，特别是在智能交通系统中，汽车牌照检测发挥了巨大的作用。
根据OpenCV相关技术，依据以下要求步骤，完成给定图像的车牌检测（参照下图）（30分）

https://blog.csdn.net/weixin_41695564/article/details/79712393

OpenCV实战（一）——简单的车牌识别
"""

import cv2 as cv
import numpy as np
import os
import sys
from python_ai.common.xcommon import *

np.random.seed(1)
title_no = 0


def rand_color():
    return (
        np.random.randint(0, 256),
        np.random.randint(0, 256),
        np.random.randint(0, 256),
    )


# ①	读取图像文件，打印图片维度和尺度
# path = 'image/car.png'
dir = '../../../../../large_data/pic/car_id'
name = 'car.png'
# name = 'A66666.jfif'
# name = 'B99999.jpg'
# name = 'H88268.jfif'
# name = 'HenanA99999.jpg'
path = os.path.join(dir, name)
img = cv.imread(path, cv.IMREAD_COLOR)
H, W, CH = img.shape
print('打印图片维度和尺度:', img.shape)
# title_no += 1
# cv.imshow(f'{title_no} img', img)

# ②	图像降噪处理
# ③	形态学处理
# ④	阈值分割
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# title_no += 1
# cv.imshow(f'{title_no} gray', gray)

# blur
blur = cv.GaussianBlur(gray, (5, 5), 0, None, 0)
# title_no += 1
# cv.imshow(f'{title_no} blur', blur)

# open
kernel = np.ones([23, 23], dtype=np.uint8)
opening = cv.morphologyEx(blur, cv.MORPH_OPEN, kernel)
# title_no += 1
# cv.imshow(f'{title_no} opening', opening)

# weighted add
sum = cv.addWeighted(gray, 1, opening, -1, 0)
title_no += 1
cv.imshow(f'{title_no} sum', sum)

# threshold
ret, thresh = cv.threshold(sum, 0, 255, cv.THRESH_OTSU + cv.THRESH_BINARY)
title_no += 1
cv.imshow(f'{title_no} thresh', thresh)

# canny
canny = cv.Canny(thresh, 100, 200)
title_no += 1
cv.imshow(f'{title_no} canny', canny)

# close and open
kernel = np.ones([10, 10], dtype=np.uint8)
res = canny
res = cv.morphologyEx(res, cv.MORPH_CLOSE, kernel)
title_no += 1
cv.imshow(f'{title_no} close', res)
res = cv.morphologyEx(res, cv.MORPH_OPEN, kernel)
title_no += 1
cv.imshow(f'{title_no} open', res)

# contours
contours, hierarchy = cv.findContours(res, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
bg = np.zeros_like(img)
areas_arr = []
for c in contours:
    cv.drawContours(bg, [c], 0, rand_color())
    area = cv.contourArea(c)
    areas_arr.append(area)
title_no += 1
cv.imshow(f'{title_no} contours', bg)

# select contour
idx_sorted = np.argsort(areas_arr)[::-1]
for idx in idx_sorted:
    c = contours[idx]
    rect = cv.boundingRect(c)
    x, y, w, h = rect
    if 2.5 < w / h < 5.5:
        break
bg = np.zeros_like(img)
cv.drawContours(bg, [c], 0, rand_color())
title_no += 1
cv.imshow(f'{title_no} select contour', bg)

# tick
img_ = img.copy()
cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
title_no += 1
cv.imshow(f'{title_no} tick it', img)

cv.waitKey(0)
cv.destroyAllWindows()
